package com.clearliang.upcloudframe;

import android.content.Context;
import android.util.Log;

import com.upyun.library.common.Params;
import com.upyun.library.common.ResumeUploader;
import com.upyun.library.common.UploadEngine;
import com.upyun.library.listener.UpCompleteListener;
import com.upyun.library.listener.UpProgressListener;
import com.upyun.library.utils.UpYunUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


/************************************************************************************/
/*****************                 又拍云工具类                      *****************/
/*****************               使用前需要配置信息                   *****************/
/************************************************************************************/
public class UpCouldUtil {
    private static class Holder {
        private static UpCouldUtil INSTANCE = new UpCouldUtil();
    }
    private void UpCouldUpLoadUtil() {
    }
    public static UpCouldUtil getInstance() {
        return Holder.INSTANCE;
    }

    private static String upYun_IP = "";            //又拍云服务器地址
    private static String SPACE = "";               //空间名
    private static String OPERATOR = "";            //操作员
    private static String PASSWORD = "";            //密码
    private static String ImagePacketPlace = "";    //图片在又拍云的文件夹，例如 image_packet
    private static String VideoPacketPlace = "";    //视频在又拍云的文件夹，例如 video_packet

    public void initUpCloud(Context context){
        List list = new ArrayList();
        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            builder = builderFactory.newDocumentBuilder();
            Document document = builder.parse(context.getAssets().open("xmlFile.xml"));
            Element element = document.getDocumentElement();
            NodeList nodeList = element.getElementsByTagName("item");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element item = (Element) nodeList.item(i);
                list.add(item.getElementsByTagName("value").item(0).getTextContent()+"");
            }

            upYun_IP = list.get(0).toString();
            SPACE = list.get(1).toString();
            OPERATOR = list.get(2).toString();
            PASSWORD = list.get(3).toString();
            ImagePacketPlace = list.get(4).toString();
            VideoPacketPlace = list.get(5).toString();

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void initUpCloud( String serverIP, String space, String operator, String password, String imagePlaceName, String videoPlaceName){
        upYun_IP = serverIP;
        SPACE = space;
        OPERATOR = operator;
        PASSWORD = password;
        ImagePacketPlace = imagePlaceName;
        VideoPacketPlace = videoPlaceName;
    }


    //上传视频成功失败的接口回调
    private OnVideoListener videoListener;
    public interface OnVideoListener {
        void successed(String originUrl,String modifyUrl);

        void failed();
    }
    public void setVideoUpLoadListener(OnVideoListener listener) {
        if (listener != null) {
            videoListener = listener;
        }
    }

    //上传图片成功失败的接口回调
    private OnImageListener imageListener;
    public interface OnImageListener {
        void successed(String url);

        void failed();
    }
    public void setImageUpLoadListener(OnImageListener listener) {
        if (listener != null) {
            imageListener = listener;
        }
    }

    private String real_path;
    /**
     * @功能 断点续传上传视频到又拍云服务器
     */
    public UpCouldUtil videoUpload(String fileName) {
        String myUri = createFileUri(fileName, VideoPacketPlace);
        int end = myUri.lastIndexOf("/");
        String upCloudName = myUri.substring(end + 1);     //32位UUID的文件名
        String upCloudUri = myUri.substring(0, end);
        File file = new File(fileName);
        //初始化断点续传
        ResumeUploader uploader = new ResumeUploader(SPACE, OPERATOR, UpYunUtils.md5(PASSWORD));
        //设置 MD5 校验
        uploader.setCheckMD5(true);
        //设置进度监听
        uploader.setOnProgressListener(new UpProgressListener() {
            @Override
            public void onRequestProgress(long bytesWrite, long contentLength) {
                LogUtil(bytesWrite + ":" + contentLength);
            }
        });

        //初始化异步音视频处理参数,参数规则详见http://docs.upyun.com/cloud/av/#_3
        Map<String, Object> processParam = new HashMap<String, Object>();

        processParam.put(ResumeUploader.Params.BUCKET_NAME, SPACE);
        processParam.put(ResumeUploader.Params.NOTIFY_URL, "http://httpbin.org/post");
        processParam.put(ResumeUploader.Params.ACCEPT, "json");
        processParam.put(ResumeUploader.Params.SOURCE, myUri);

        JSONArray array = new JSONArray();

        JSONObject json = new JSONObject();
        try {
            json.put(ResumeUploader.Params.TYPE, "video");
            json.put(ResumeUploader.Params.AVOPTS, "/s/240p(4:3)/as/1/r/30");
            json.put(ResumeUploader.Params.RETURN_INFO, "true");
            //输出文件保存路径（同一个空间下），如果没有指定，系统自动生成在同空间同目录下
            json.put(ResumeUploader.Params.SAVE_AS, upCloudUri + "/modify/" + "modify_" + upCloudName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //real_path = upCloudUri+"/modify/"+"modify_"+upCloudName;
        real_path = upCloudUri + "/" + upCloudName;

        /*JSONObject json2 = new JSONObject();
        json2.put(ResumeUploader.Params.TYPE, "video");
        json2.put(ResumeUploader.Params.AVOPTS, "/s/240p(4:3)/as/1/r/30");
        json2.put(ResumeUploader.Params.RETURN_INFO, "true");
        json2.put(ResumeUploader.Params.SAVE_AS, "testProcess2.mp4");

        array.put(json2);*/
        array.put(json);

        processParam.put(ResumeUploader.Params.TASKS, array);


        //第二个参数是我文件在又拍云保存的路径
        LogUtil("文件在又拍云保存的路径:" + myUri);
        uploader.upload(file, myUri, null, processParam, new UpCompleteListener() {
            @Override
            public void onComplete(boolean isSuccess, String result) {
                LogUtil("isSuccess:" + isSuccess + "  result:" + result);
                if (isSuccess) {
                    if (videoListener != null) {
                        String str = upYun_IP + real_path.substring(1);
                        String modifyString = str.substring(0,str.lastIndexOf("/"))
                                + "/modify/modify_"
                                + str.substring(str.lastIndexOf("/")+1);
                        videoListener.successed(str,modifyString);
                    }
                } else {
                    LogUtil("Upload avatar failed--------------" + result);
                    if (videoListener != null) {
                        videoListener.failed();
                    }
                }
            }
        });
        return Holder.INSTANCE;
    }

    /**
     * @功能 表单上传（本地签名方式）图片到又拍云服务器
     */
    public UpCouldUtil imageUpload(String fileName) {
        String myUri = createFileUri(fileName, ImagePacketPlace);
        int end = myUri.lastIndexOf("/");
        String upCloudName = myUri.substring(end + 1);     //32位UUID的文件名
        String upCloudUri = myUri.substring(0, end);
        File file = new File(fileName);

        Map<String, Object> paramsMap = new HashMap<>();
        //上传空间
        paramsMap.put(Params.BUCKET, SPACE);
        //保存路径，任选其中一个
        paramsMap.put(Params.SAVE_KEY, myUri);
        //添加 CONTENT_LENGTH 参数使用大文件表单上传
        paramsMap.put(Params.CONTENT_LENGTH, file.length());

        paramsMap.put(Params.CONTENT_MD5, UpYunUtils.md5Hex(file));

        //可选参数（详情见api文档介绍）
        paramsMap.put(Params.RETURN_URL, "httpbin.org/post");
        //进度回调，可为空
        UpProgressListener progressListener = new UpProgressListener() {
            @Override
            public void onRequestProgress(final long bytesWrite, final long contentLength) {
                //LogUtils.e((100 * bytesWrite) / contentLength + "%");
                //LogUtils.e(bytesWrite + "::" + contentLength);
            }
        };

        //结束回调，不可为空
        UpCompleteListener completeListener = new UpCompleteListener() {
            @Override
            public void onComplete(boolean isSuccess, String result) {
                LogUtil("isSuccess:" + isSuccess + "\n" + "  result:" + result);
                if (isSuccess) {
                    if (imageListener != null) {
                        imageListener.successed(upYun_IP + real_path.substring(1));
                    }
                } else {
                    LogUtil("Upload avatar failed--------------" + result);
                    if (imageListener != null) {
                        imageListener.failed();
                    }
                }
            }
        };

        //初始化JSONArray，上传预处理（异步）参数详见 http://docs.upyun.com/cloud/image/#_6，
        JSONArray array = new JSONArray();

        //初始化JSONObject
        JSONObject json = new JSONObject();
        //json 添加 name 属性
        try {
            json.put("name", "thumb");
            json.put("x-gmkerl-thumb", "/fw/300/unsharp/true/quality/80/format/png");
            json.put("save_as", upCloudUri + "/modify/" + "modify_" + upCloudName);
            json.put("notify_url", "http://httpbin.org/post");

            //real_path = upCloudUri+"/modify/"+"modify_"+upCloudName;
            real_path = upCloudUri + "/" + upCloudName + "!small";
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //将json 对象放入 JSONArray
        array.put(json);

        //添加异步作图参数 APPS
        paramsMap.put("apps", array);

        //表单上传（本地签名方式）
        UploadEngine.getInstance().formUpload(file, paramsMap, OPERATOR, UpYunUtils.md5(PASSWORD), completeListener, progressListener);

        return Holder.INSTANCE;
    }

    /**
     * 创建资源的唯一标识
     */
    private String createFileUri(String fileUri, String folderName) {
        Calendar cal = Calendar.getInstance();
        String name = getUUID();//32位_同时也是文件的名字，后缀需要另外加入
        String uri = File.separator
                + folderName + File.separator
                + cal.get(Calendar.YEAR) + File.separator
                + (cal.get(Calendar.MONTH) + 1) + File.separator
                + (cal.get(Calendar.DAY_OF_MONTH)) + File.separator + name + "." + getSuffix(fileUri);
        return uri;
    }

    //获取某一路径下文件的后缀名
    private String getSuffix(String fileUri) {
        int start = fileUri.lastIndexOf(".");
        if (start != -1) {
            return fileUri.substring(start + 1);
        } else {
            return null;
        }
    }

    /**
     * 获取UUID,创建唯一标识
     */
    private String getUUID() {
        return java.util.UUID.randomUUID().toString();
    }

    private void LogUtil(String msg) {
        Log.e("又拍云信息：", msg);
    }


}
